<?php

namespace App\Admin\Controllers;

use App\Admin\Requests\UploadImageRequest;

class ImageController extends Controller
{
    /**
     * @api               {post} upload 統一圖片上傳接口
     * @apiGroup          Upload
     * @apiName           /v1/upload
     * @apiVersion        1.0.0
     * @apiDescription    統一圖片上傳接口,表單提交需要添加enctype="multipart/form-data"，默認filename=file
     * @apiHeader {String} Authorization {Bearer access_token} 必須
     * @apiParam {String} type 圖片類型[goods,appeal,help,notice,payment,order,avatar]
     * @apiSuccessExample 成功響應
     *          {
     *           "status": "success",
     *           "message": "Image URI",
     *           "data": []
     *          }
     * @apiErrorExample   失敗響應
     *            {
     *             "status": "failure",
     *             "message": "error message",
     *             "data": []
     *            }
     */
    public function upload(UploadImageRequest $request)
    {
        $type = $request->input('type');
        $img  = $request->file('file');
        if (!$this->validateExt($img->extension())) {
            return $this->failure('圖片類型不合法');
        }

        $path = $img->store($this->getStoreDirByType($type), 'upload');

        return $this->success('', [
            'uri'    => $path,
            'domain' => config('filesystems.disks.upload.url'),
            'url'    => config('filesystems.disks.upload.url') . "/" . $path,
        ]);
    }

    /**
     * 檢測文件後綴是否合法
     */
    public function validateExt($ext)
    {
        $ext = strtolower($ext);
        if (!in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])) {
            return false;
        }
        return true;
    }

    public function getStoreDirByType($type)
    {
        return "/{$type}/" . date('Ymd');
    }

}